/**
 * @author (c) 2020. Chen_9g jleopard@126.com.
 * @date 2021/10/24  19:00
 * @version 1.0
 *
 * <p>
 * Find a way for success and not make excuses for failure.
 * </p>
 */
package top.xzxsrq.exsyExcelTool.style;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import top.xzxsrq.exsyExcelTool.utils.EasyExcelUtilsZX;

import java.util.List;
import java.util.function.Consumer;

/**
 * 单元格样式
 * EasyExcel.write(response.getOutputStream(), emptyClassClass)
 * .registerWriteHandler(new ContentCellSetStyle()) // 样式位置
 * .sheet("供货计划汇总表")
 * .doWrite(collect);
 */
public class ContentCellSetStyle<T> implements CellWriteHandler {

    private final Consumer<CellStyleParams<T>> function;

    private int headRowSum = 1;

    private final List<T> list;

    public ContentCellSetStyle(Consumer<CellStyleParams<T>> function, List<T> list) {
        this.function = function;
        this.list = list;
    }

    public ContentCellSetStyle(Consumer<CellStyleParams<T>> function, Class<?> head, List<T> list) {
        this.function = function;
        this.list = list;
        this.headRowSum = EasyExcelUtilsZX.getHeadMaxRowNumber(head);
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        WriteCellData<?> firstCellData = context.getFirstCellData();
        Cell cell = context.getCell();
        Head head = context.getHeadData();
        WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
        int rowIndex = cell.getRowIndex() - headRowSum;
        if (rowIndex < 0) {
            return;
        }
        CellStyleParams<T> item = new CellStyleParams<>();
        item.setCell(cell);
        item.setRow(list.get(rowIndex));
        item.setColumnIndex(cell.getColumnIndex());
        item.setHead(head);
        item.setRowIndex(rowIndex);
        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
        item.setWorkbook(workbook);
        item.setWriteCellData(firstCellData);
        function.accept(item);
    }
}
